package com.stake.web.controller;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.xml.sax.InputSource;

import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.constant.ApplicationConstants;
import com.google.code.linkedinapi.client.constant.LinkedInApiUrls.LinkedInApiUrlBuilder;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInApiConsumer;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.schema.HttpHeader;
import com.google.code.linkedinapi.schema.Person;
import com.stake.entity.UserInfo;

@Controller
@RequestMapping("/public/linkedin")
public class LinkedInOauthWebController {
	
	@Autowired
	@Qualifier("persistenceManagerFactory") 
	PersistenceManagerFactory persistenceManagerFactory;
	
	@Autowired
	@Qualifier("authenticationManager") 
	AuthenticationManager authenticationManager;
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/authRedirect.htm")
	public ModelAndView handleRedirect(HttpServletRequest request, HttpSession session)
			throws Exception {
		LinkedInAccessToken accessToken = (LinkedInAccessToken) session.getAttribute("linkedInaccessToken");
		final String consumerKeyValue = "57vupwf7qm04";
		final String consumerSecretValue = "aHh3om7Zf9q5esFS";
		LinkedInApiConsumer apiConsumer = new LinkedInApiConsumer(consumerKeyValue, consumerSecretValue);
		final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(consumerKeyValue, consumerSecretValue);
		final LinkedInApiClient client = factory.createLinkedInApiClient(accessToken);
		
		System.out.println("Fetching profile for current user.");
		Person profile = client.getProfileForCurrentUser();
		
		
		LinkedInApiUrlBuilder builder2 = new LinkedInApiUrlBuilder("http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,picture-url)");
		String                apiUrl  = builder2.buildUrl();
        System.out.println("printing email data"); 
		//////////////////////////////////////
        XPathFactory  xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        XPathExpression exp = null;
        String pictureUrl = null;
        String headline = null;
        try {
			exp = xpath.compile("//picture-url");
			InputSource inputSource = new InputSource(callApiMethod(apiUrl, apiConsumer, client));
			pictureUrl = exp.evaluate(inputSource); 
			exp = xpath.compile("//headline");
			headline = exp.evaluate(inputSource);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		
		
		
		//////////////////////////////////////
		LinkedInApiUrlBuilder builder = new LinkedInApiUrlBuilder("http://api.linkedin.com/v1/people/~/email-address"); 
        String                apiUrl2  = builder.buildUrl();
        System.out.println("printing email data"); 
        String emailAddress = null;
        try {
			exp = xpath.compile("//email-address");
			emailAddress = exp.evaluate(new InputSource(callApiMethod(apiUrl2, apiConsumer, client))); 
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
        System.out.println("email address : " + emailAddress); 
		System.out.println("first name : " + profile.getFirstName());
		
		PersistenceManager manager = persistenceManagerFactory.getPersistenceManager();
		
		Query query = manager.newQuery(UserInfo.class);
		query.setFilter("email == emailParam");
		query.declareParameters("String emailParam");
		List<UserInfo> userEntities = (List<UserInfo>) query.execute(emailAddress);  
		UserInfo newUser = new UserInfo();
		if(userEntities.size() > 0){
			// user already exists
			newUser = userEntities.get(0);
		} else {
			List<String> authorities = new ArrayList<String>();
			authorities.add("ROLE_USER");
			newUser.setAuthorities(authorities);
			newUser.setEnabled(Boolean.TRUE);
			newUser.setUserName(emailAddress);
			newUser.setEmail(emailAddress);
			newUser.setFirstName(profile.getFirstName());
			newUser.setLastName(profile.getLastName());
			newUser.setPassword("linkedin");
			newUser.setQanswered(Boolean.FALSE);
			newUser = manager.makePersistent(newUser);
			
		}
		newUser.setLinkedInAccessToken(accessToken.getToken());
		newUser.setLinkedInTokenSecret(accessToken.getTokenSecret());
		newUser.setLinkedInTokenExpiry(accessToken.getExpirationTime());
		
        manager.close();
		UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(emailAddress, newUser.getPassword());
		Authentication authentication = authenticationManager.authenticate(authToken);
		SecurityContextHolder.getContext().setAuthentication(authentication);
		return new ModelAndView("auth_success_close");
		
	}
	
	/**
    *
    *
    * @param apiUrl
    * @param expected
    * @param httpHeaders
    *
    * @return
    */
   protected InputStream callApiMethod(String apiUrl, LinkedInApiConsumer apiConsumer, LinkedInApiClient client) {
	   List<HttpHeader> httpHeaders = Collections.emptyList();
	   Map<String, String> requestHeaders = new HashMap<String, String>(); 
	   /** Field description */
	    final String GZIP_ENCODING = "gzip";
       // by default we compress contents
       requestHeaders.put("Accept-Encoding", "gzip, deflate");
	   int expected = HttpURLConnection.HTTP_OK; 
       try {
           LinkedInOAuthService oAuthService =
               LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(apiConsumer.getConsumerKey(),
                   apiConsumer.getConsumerSecret());
           URL               url     = new URL(apiUrl);
           HttpURLConnection request = (HttpURLConnection) url.openConnection();

           if (ApplicationConstants.CONNECT_TIMEOUT > -1) {
               request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT);
           }

           if (ApplicationConstants.READ_TIMEOUT > -1) {
               request.setReadTimeout(ApplicationConstants.READ_TIMEOUT);
           }

           for (String headerName : requestHeaders.keySet()) {
               request.setRequestProperty(headerName, requestHeaders.get(headerName));
           }
           
           for (HttpHeader header : httpHeaders) {
               request.setRequestProperty(header.getName(), header.getValue());
           }
           
           oAuthService.signRequestWithToken(request, client.getAccessToken());
           request.connect();

           if (request.getResponseCode() != expected) {
              System.out.println("Error Occourred"); 
              return null;
           } else {
               return getWrappedInputStream(request.getInputStream(),
                                            GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()));
           }
       } catch (IOException e) {
           throw new LinkedInApiClientException(e);
       }
   }
   
   /**
    * Method description
    *
    *
    * @param is
    * @param gzip
    * @return
    * @throws IOException
    */
   protected InputStream getWrappedInputStream(InputStream is, boolean gzip) throws IOException {
       if (gzip) {
           return new BufferedInputStream(new GZIPInputStream(is));
       } else {
           return new BufferedInputStream(is);
       }
   }

}
